module Filler
  def fill_song(query)
    c = Component.find_by_title(query)
    return c ? [c.resource, c.body.gsub('\\n',"\n")] : nil
  end

  def fill_verses(query)
    if m = query.match(/^(\D+)\s*(\d+)[:：](\d+)\s*[-－]\s*(\d+)[:：](\d+)$/u) 
      book, chapter1, verse1, chapter2, verse2 = m[1..-1]
    elsif m = query.match(/^(\D+)\s*(\d*)[:：](\d*)\s*[-－]\s*(\d+)$/u) 
      book, chapter1, verse1, verse2 = m[1..-1]
      chapter2 = chapter1
    elsif m = query.match(/^(\D+)\s*(\d+)[:：](\d+)$/u)
      book, chapter1, verse1 = m[1..-1]
      chapter2, verse2 = chapter1, verse1
    else
      return
    end

    bb = BibleBook.find_by_name_zh(book) || BibleBook.find_by_abbr_zh(book) 
    v1 = bb.verses.find_by_chapter_and_verse(chapter1, verse1)
    v2 = bb.verses.find_by_chapter_and_verse(chapter2, verse2)
    verses = BibleVerse.find_all_by_id(v1.id..v2.id).collect{ |v| "#{v.verse} #{v.text_zh}" }

    # TODO a better splitter
#    verse_str = ""
#    lines = 0
#    verse_pages = verses.inject([]) do |pages, v|
#      n = v.length / 11 + 1
#      lines += n
#      if lines > 8
#        pages << verse_str
#        verse_str = v + "\n"
#        lines = 0
#      else
#        verse_str += v + "\n"
#      end
#    end
#
#    return ['bible', verse_pages.join("\n")]
    return ['bible', verses.join("\n")]
  end

end
